package com.fallingsnow.sometask

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.fallingsnow.sometask.databinding.ActivityMainBinding
import com.fallingsnow.sometask.ui.HomeActivity
import com.fallingsnow.sometask.utils.SkipAdsTimesUtil

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var binding: ActivityMainBinding;
    private lateinit var skipTimerTextView: TextView;

    private lateinit var skipAdsTimes: SkipAdsTimesUtil;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val countDownTimer: Long = resources.getInteger(R.integer.skipAdsTimer).toLong()

        println("countDownTimer: $countDownTimer")

        binding = ActivityMainBinding.inflate(layoutInflater)
        enableEdgeToEdge()


        // 开启定时器
        // 1. 基于 CountDownTimer实现
        skipTimerTextView = binding.skipAdTimer
        skipAdsTimes = SkipAdsTimesUtil(skipTimerTextView, countDownTimer, finished = ::jumpToHome);
        skipAdsTimes.start()


        // start skip timer
        skipTimerTextView.setOnClickListener(this)

        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            skipTimerTextView.id -> {
                jumpToHome()
            }
        }
    }

    private fun jumpToHome() {
        // 清除定时器
        skipAdsTimes.cancel()
        // 跳转目标Activity
        val homeActivity = Intent(this, HomeActivity::class.java)
        startActivity(homeActivity)
        // 关闭当前Activity
        finish()
    }
}